package com.ruoyi.zhmk.controller;

import java.util.List;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.zhmk.domain.ZhmkDept;
import com.ruoyi.zhmk.service.IZhmkDeptService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.domain.Ztree;

/**
 * 人员部门Controller
 * 
 * @author sxl
 * @date 2021-06-10
 */
@Controller
@RequestMapping("/zhmk/dept")
public class ZhmkDeptController extends BaseController
{
    private String prefix = "zhmk/dept";

    @Autowired
    private IZhmkDeptService zhmkDeptService;

    @RequiresPermissions("zhmk:dept:view")
    @GetMapping()
    public String dept()
    {
        return prefix + "/dept";
    }

    /**
     * 查询人员部门树列表（自己）
     */
    @RequiresPermissions("zhmk:dept:list")
    @PostMapping("/list")
    @ResponseBody
    public List<ZhmkDept> list(ZhmkDept zhmkDept)
    {
        List<ZhmkDept> list = zhmkDeptService.selectZhmkDeptList(zhmkDept);
        return list;
    }

    /**
     * 导出人员部门列表
     */
    @RequiresPermissions("zhmk:dept:export")
    @Log(title = "人员部门", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ZhmkDept zhmkDept)
    {
        List<ZhmkDept> list = zhmkDeptService.selectZhmkDeptList(zhmkDept);
        ExcelUtil<ZhmkDept> util = new ExcelUtil<ZhmkDept>(ZhmkDept.class);
        return util.exportExcel(list, "人员部门数据");
    }

    /**
     * 新增人员部门
     */
    @GetMapping(value = { "/add/{deptId}", "/add/" })
    public String add(@PathVariable(value = "deptId", required = false) Long deptId, ModelMap mmap)
    {
        //deptId=''   或者   deptId='0'
        mmap.put("zhmkDept", zhmkDeptService.selectZhmkDeptById(deptId));
        return prefix + "/add";
    }
   /*@GetMapping("/add/{parentId}")
    public String add(@PathVariable("parentId") Long parentId, ModelMap mmap)
    {
        if (!ShiroUtils.getSysUser().isAdmin())  //获取登录用户信息，userId存在,如果不是管理员
        {
            parentId = ShiroUtils.getSysUser().getDeptId();
        }
        mmap.put("dept", zhmkDeptService.selectZhmkDeptById(parentId));
        return prefix + "/add";
    }*/

    /**
     * 新增保存人员部门
     */
    @RequiresPermissions("zhmk:dept:add")
    @Log(title = "人员部门", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated ZhmkDept zhmkDept)
    {
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(zhmkDeptService.checkDeptNameUnique(zhmkDept)))
        {
            return error("新增部门'" + zhmkDept.getDeptName() + "'失败，部门名称已存在");
        }
        zhmkDept.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(zhmkDeptService.insertZhmkDept(zhmkDept));
    }

    /**
     * 修改人员部门
     */
    @GetMapping("/edit/{deptId}")
    public String edit(@PathVariable("deptId") Long deptId, ModelMap mmap)
    {
        ZhmkDept zhmkDept = zhmkDeptService.selectZhmkDeptById(deptId);
        if (StringUtils.isNotNull(zhmkDept) && 100L == deptId)
        {
            zhmkDept.setParentName("无");
        }
        mmap.put("zhmkDept", zhmkDept);
        return prefix + "/edit";
    }

    /**
     * 修改保存人员部门
     */
    @RequiresPermissions("zhmk:dept:edit")
    @Log(title = "人员部门", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated ZhmkDept zhmkDept)
    {
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(zhmkDeptService.checkDeptNameUnique(zhmkDept)))
        {
            return error("修改部门'" + zhmkDept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (zhmkDept.getParentId().equals(zhmkDept.getDeptId()))
        {
            return error("修改部门'" + zhmkDept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, zhmkDept.getStatus())
                && zhmkDeptService.selectNormalChildrenDeptById(zhmkDept.getDeptId()) > 0)
        {
            return AjaxResult.error("该部门包含未停用的子部门！");
        }
        zhmkDept.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(zhmkDeptService.updateZhmkDept(zhmkDept));
    }

    /**
     * 删除
     */
    @RequiresPermissions("zhmk:dept:remove")
    @Log(title = "人员部门", businessType = BusinessType.DELETE)
    @GetMapping("/remove/{deptId}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("deptId") Long deptId)
    {
        if (zhmkDeptService.selectDeptCount(deptId) > 0)
        {
            return AjaxResult.warn("存在下级部门,不允许删除");
        }
        if (zhmkDeptService.checkDeptExistUser(deptId))
        {
            return AjaxResult.warn("部门存在用户,不允许删除");
        }
        return toAjax(zhmkDeptService.deleteZhmkDeptById(deptId));
    }

    /**
     * 校验部门名称
     */
    @PostMapping("/checkDeptNameUnique")
    @ResponseBody
    public String checkDeptNameUnique(ZhmkDept dept)
    {
        return zhmkDeptService.checkDeptNameUnique(dept);
    }

    /**
     * 选择人员部门树
     */
    @GetMapping(value = { "/selectDeptTree/{deptId}", "/selectDeptTree/{deptId}/{excludeId}" })
    public String selectDeptTree(@PathVariable("deptId") Long deptId,
                                 @PathVariable(value = "excludeId", required = false) String excludeId, ModelMap mmap)
    {
        mmap.put("zhmkDept", zhmkDeptService.selectZhmkDeptById(deptId)); //我选择的父节点deptId
        mmap.put("excludeId", excludeId);//为修改树结构排除自己deptId存储的数据,跳到tree.html页面，存储deptID,deptName
        return prefix + "/tree";
    }

    /**
     * 加载人员部门树列表 （自己）
     */
    /*@GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData()
    {
        List<Ztree> ztrees = zhmkDeptService.selectZhmkDeptTree();
        return ztrees;
    }*/
    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData()
    {
        List<Ztree> ztrees = zhmkDeptService.selectDeptTree(new ZhmkDept());
        return ztrees;
    }

    /**
     * 加载部门列表树（排除下级）
     */
    @GetMapping("/treeData/{excludeId}")
    @ResponseBody
    public List<Ztree> treeDataExcludeChild(@PathVariable(value = "excludeId", required = false) Long excludeId)
    {
        ZhmkDept dept = new ZhmkDept();
        dept.setDeptId(excludeId);
        List<Ztree> ztrees = zhmkDeptService.selectDeptTreeExcludeChild(dept);
        return ztrees;
    }

}
